document.getElementById('message-form').addEventListener('submit', function(event) {
    event.preventDefault();

    var nickname = document.getElementById('nickname').value;
    var message = document.getElementById('message').value;

    if (message.trim() === '') {
        alert('消息不能为空');
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'submit_message.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            document.getElementById('message').value = '';
            loadChat();
        }
    };

    var data = 'nickname=' + encodeURIComponent(nickname) + '&message=' + encodeURIComponent(message);
    xhr.send(data);
});

function loadChat() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'chat.php', true);

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            document.getElementById('chat-box').innerHTML = xhr.responseText;
        }
    };

    xhr.send();
}

// 自动加载新消息
setInterval(loadChat, 5000);

